package civicinity.ist.psu.edu.events;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.adapter.CivicinityShareListViewAdapter;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.rssfeed.RSSItem;
import civicinity.ist.psu.edu.share.ShareItem;
import civicinity.ist.psu.edu.utils.CivicinityDrawableManager;
import civicinity.ist.psu.edu.utils.DownloadHandler;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class CivicinityEvents extends Activity {

	//private GridView gridView;
	private String[] mEventStr = {"football", "art festival", "art festival", "new year", "ist event"};
	
	private ArrayList<EventItem> mArr;
	
	private ProgressBar mSpinner;
	private TextView mLoadingTxt;
	
	private ListView mListView;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.civicinity_event_contest);
	    
	    mArr = new ArrayList<EventItem>();
	    
	    mSpinner = (ProgressBar)findViewById(R.id.spinner);
	    mLoadingTxt = (TextView)findViewById(R.id.loading_text);
	    
	    // not using gridview?
	    // I thought it is okay, but well...
	    //gridView = (GridView)findViewById(R.id.data_grid);
	    // instead using listview
	    mListView = (ListView)findViewById(R.id.data_grid);
	   
	    new downloadEventInfo().execute();
	    // TODO Auto-generated method stub
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		mListView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(CivicinityEvents.this, CivicinityEventSelected.class);
				intent.putExtra("event_id", mArr.get(position).getID());
				intent.putExtra("event_title", mArr.get(position).getTitle());
				intent.putExtra("event_description", mArr.get(position).getDescription());
				intent.putExtra("event_feed_url", mArr.get(position).getEventFeedUrl());
				intent.putExtra("event_active", mArr.get(position).getIsEventActive());
				startActivity(intent);
			}
			
		});
		
		/*
		gridView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(CivicinityEvents.this, CivicinityEventSelected.class);
				intent.putExtra("event_id", mArr.get(position).getID());
				intent.putExtra("event_title", mArr.get(position).getTitle());
				intent.putExtra("event_description", mArr.get(position).getDescription());
				startActivity(intent);
			}
			
		});
		*/
	}
	
	class downloadEventInfo extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			DownloadHandler dHandler = new DownloadHandler();
			String getResponse = dHandler.downloadJson(Constants.DOWNLOAD_EVENT_INFO);
			
			int currentStatusValue = 0;
			
			try{
				JSONObject jObj = new JSONObject(getResponse);
				
				if(jObj.getBoolean("success")) {
					JSONArray jsonAry = new JSONArray(jObj.getString("results"));
					
					for(int i = 0; i < jsonAry.length(); i++){
						
						EventItem item = new EventItem();
						item.setID(Integer.parseInt(jsonAry.getJSONObject(i).getString("event_id")));
						item.setTitle(jsonAry.getJSONObject(i).getString("event_title"));
						item.setDescription(jsonAry.getJSONObject(i).getString("event_description"));
						item.setEventFeedUrl(jsonAry.getJSONObject(i).getString("event_feed_url"));
						item.setEventActive(jsonAry.getJSONObject(i).getInt("event_active"));
						item.setStartDate(Long.parseLong(jsonAry.getJSONObject(i).getString("event_date_from")));
						item.setEndDate(Long.parseLong(jsonAry.getJSONObject(i).getString("event_date_to")));
						// event status
						// 1 - current, 2 - upcoming, 3 - past
						item.setEventStatus(jsonAry.getJSONObject(i).getInt("status"));
						if(i == 0) {
							item.setHeader(true);
							currentStatusValue = jsonAry.getJSONObject(i).getInt("status");
						}
						else {
							if(currentStatusValue == jsonAry.getJSONObject(i).getInt("status")) {
								item.setHeader(false);
								currentStatusValue = jsonAry.getJSONObject(i).getInt("status");
							}
							else {
								item.setHeader(true);
								currentStatusValue = jsonAry.getJSONObject(i).getInt("status");
							}
						}
				
						mArr.add(item);
					
					}
					Log.d("K", "download event info.");
				}
				
				//mDB.setShareOthers(mShareOthersArr);
				
			} catch(Exception e){}
			
			
			return null;
		}
		
		@Override
	  	protected void onPostExecute(Void unused) {
			
			mSpinner.setVisibility(View.GONE);
			mLoadingTxt.setVisibility(View.GONE);
		
			ImageAdapter adapter = new ImageAdapter(CivicinityEvents.this, R.layout.grid_item, mArr);
			mListView.setAdapter(adapter);
			//gridView.setAdapter(adapter);
		}
	}
	
	class ImageAdapter extends BaseAdapter {

		private Context mContext;
		private LayoutInflater mInflater;
		private int mLayout;
		private ArrayList<EventItem> eArr = new ArrayList<EventItem>();
		
		public ImageAdapter(Context context, int layout, ArrayList<EventItem> arr) {
			mContext = context;
			mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mLayout = layout;
			eArr = arr;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return eArr.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if(convertView == null)
				convertView = mInflater.inflate(mLayout, parent, false);
			
			ImageView gImage = (ImageView)convertView.findViewById(R.id.grid_item_image);
			TextView gTitle = (TextView)convertView.findViewById(R.id.grid_item_text1);
			TextView gDate = (TextView)convertView.findViewById(R.id.grid_item_text2);
			TextView gHeader = (TextView)convertView.findViewById(R.id.item_header);
			ProgressBar gSpinner = (ProgressBar)convertView.findViewById(R.id.grid_spinner);
			
			// whether to show the header or not.
			if(eArr.get(position).getHeader()) {
				if(eArr.get(position).getEventStatus() == 1) {
					gHeader.setText("Current events");
				}
				else if(eArr.get(position).getEventStatus() == 2) {
					gHeader.setText("Upcoming events");
				}
				else {
					gHeader.setText("Past events");
				}
				gHeader.setVisibility(View.VISIBLE);
			}
			else {
				gHeader.setVisibility(View.GONE);
			}

			// show image
			CivicinityDrawableManager dm = new CivicinityDrawableManager(CivicinityEvents.this, gSpinner, gImage);
			dm.fetchDrawableOnThread(Constants.DOWNLOAD_EVENT_IMAGE + eArr.get(position).getID() + ".jpg");
			
			// show text on the textViews.
			gTitle.setText(eArr.get(position).getTitle());
			
			Log.i("K", "startDate : " + eArr.get(position).getStartDate());
			
			SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
	        Date startDate = new Date(eArr.get(position).getStartDate() * 1000);
	        Date endDate = new Date(eArr.get(position).getEndDate() * 1000);
	        gDate.setText(sdf.format(startDate) + " ~ " + sdf.format(endDate));
	        
			if(eArr.get(position).getTitle().equals("Daily Events by CDT")) {
				gDate.setText("Today");
			}
			
			// TODO Auto-generated method stub
			return convertView;
		}
	}

}
